﻿using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using Whoever.Framework.Struct;

namespace Whoever.Patterns.Data.Infrastructure
{
    public static class PagerFactory<TEntity>
    {
        public static IQueryable<TEntity> GetPaged(IQueryable<TEntity> result, ref Pager pager)
        {
            if (pager.sortDir == null || pager.page == 0 || pager.maxResults == 0)
                throw new Exception("Pager have incorrect data");

            PropertyInfo defaultProperty = typeof(TEntity).GetProperties().Where(p => !p.GetGetMethod().IsVirtual && p.GetCustomAttributes(typeof(NotMappedAttribute), true).Count() == 0).First();

            pager.totalResults = result.Count();
            var sortedResults = pager.sortDir == "ASC" ? result.AsQueryable().OrderBy(pager.sort ?? defaultProperty.Name) : result.AsQueryable().OrderByDescending(pager.sort ?? defaultProperty.Name);
            var pagedResults = sortedResults.Skip((pager.page - 1) * pager.maxResults).Take(pager.maxResults);

            return pagedResults;
        }
    }
}
